package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.dao.HCarReserveMapper;
import com.flea.hclv.model.dao.HGuideMapper;
import com.flea.hclv.model.dao.HQrManageMapper;
import com.flea.hclv.model.entity.HCarReserve;
import com.flea.hclv.model.entity.HGuide;
import com.flea.hclv.model.entity.HQrManage;
import com.flea.hclv.model.entity.HResourceRelation;
import com.flea.hclv.service.HQrManageService;
import com.flea.hclv.util.PropertiesUtil;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.bean.FleaPage;
import com.flea.system.dao.OrgUserMapper;
import com.flea.system.dao.WebFileuploadMapper;
import com.flea.system.entity.OrgDept;
import com.flea.system.entity.OrgUser;
import com.flea.system.entity.WebFileupload;
import com.flea.system.platform.session.FleaOrgUtils;
import com.flea.system.utils.FleaStringUtils;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.util.List;

/**
 * @program: project
 * @description: 二维码管理
 * @author: shiliqiang
 * @create: 2018-11-01 11:15
 * @version: 1.0
 */
@Service
public class HQrManageServiceImpl implements HQrManageService {

    @Autowired
    private HQrManageMapper hQrManageMapper;

    @Autowired
    private WebFileuploadMapper fileUploadMapper;
    @Autowired
    private OrgUserMapper orgUserMapper;
    @Autowired
    private HGuideMapper hGuideMapper;
    @Autowired
    private HCarReserveMapper hCarReserveMapper;


    @Override
    public ServerResponse<List<HQrManage>> selectByUserId(String userId) {
        List<HQrManage> list = hQrManageMapper.selectByCreateUser(userId);
        return ServerResponse.createBySuccess(list);
    }

//    @Override
//    public ServerResponse<FleaPage<HQrManage>> selectFleet(FleaPage<HQrManage> paging, String carReverseId) {
//        RowBounds rowBounds = new RowBounds(paging.getCurPage(),paging.getPageSize());
//        HCarReserve reserve = hCarReserveMapper.selectByPrimaryKey(carReverseId);
//        if (reserve==null){
//            return ServerResponse.
//        }
//        return null;
//    }

    @Override
    public ServerResponse<List<HQrManage>> selectByGuideId(String guideId, OrgDept currentDept) {
        if (currentDept==null){
            return ServerResponse.createByErrorMessage("部门信息不能为空");
        }
        HGuide hGuide = hGuideMapper.selectByPrimaryKey(guideId);
        String userId = hGuide.getUserId();
        String serviceType = currentDept.getServiceType();
        if (HConstant.D_SERVICE_ORG_GROUP.equals(serviceType) || HConstant.D_SERVICE_ORG_SUPPLIER.equals(serviceType)){
            ServerResponse<List<HQrManage>> response = this.selectByUserId(userId);
            List<HQrManage> data = response.getData();
            if (data.size()==0){
                return ServerResponse.createByErrorMessage("请联系导游上传支付账号");
            }
            return response;
        }


        return ServerResponse.createByErrorMessage("没有权限");
    }

    @Override
    public ServerResponse<HQrManage> selectById(String id) {
        if (id == null) {
            return ServerResponse.createByErrorMessage("id不能为空");
        }
        HQrManage hQrManage = hQrManageMapper.selectByPrimaryKey(id);
        if (hQrManage != null) {
            return ServerResponse.createBySuccess(hQrManage);
        }
        return ServerResponse.createByErrorMessage("没有找到该记录");
    }

    @Override
    public ServerResponse<FleaPage<HQrManage>> getAll(String personName, int curPage, int pageSize) {
        RowBounds rowBounds = new RowBounds(curPage, pageSize);
        List<HQrManage> hQrManages = hQrManageMapper.getAll(rowBounds, personName);
        FleaPage<HQrManage> hQrManageFleaPage = new FleaPage<>(hQrManages);
        return ServerResponse.createBySuccess(hQrManageFleaPage);
    }

    @Override
    public ServerResponse<List<HQrManage>> getQrListByDeptId(OrgDept currentUserDept) {
       if (currentUserDept == null) {
            return ServerResponse.createByErrorMessage("部门不能为空");
        }
        String deptId = currentUserDept.getDeptUuid();
        List<HQrManage> hQrManages = hQrManageMapper.selectQrListByDeptId(deptId);
        List<HQrManage> list = Lists.newArrayList();
        for (HQrManage hQrManage : hQrManages) {
            HQrManage qr = new HQrManage();
            qr.setId(hQrManage.getId());
            qr.setPersonPhone(hQrManage.getPersonPhone());
            qr.setPersonName(hQrManage.getPersonName());
            qr.setAccountNumber(hQrManage.getAccountNumber());
            qr.setUuid(hQrManage.getUuid());
            OrgUser user = orgUserMapper.selectByPrimaryKey(hQrManage.getCreateUser());
            qr.setCreateUser(user.getUserName());
            qr.setCreateTime(hQrManage.getCreateTime());
            qr.setModifyUser(hQrManage.getModifyUser());
            qr.setModifyTime(hQrManage.getCreateTime());
            qr.setRemark(hQrManage.getRemark());
            qr.setQrCodePath(hQrManage.getQrCodePath());
            qr.setQrCodeId(hQrManage.getQrCodeId());
            OrgDept dept = FleaOrgUtils.getOrgDeptByDeptUuid(deptId);
            qr.setUuid(dept != null ? dept.getDeptName() : StringUtils.EMPTY);
            String type = hQrManage.getType();
            qr.setType(type);
            list.add(qr);
        }
        return ServerResponse.createBySuccess(list);
    }

    @Override
    public ServerResponse<String> delete(List<String> ids) {
            if (ids == null) {
            return ServerResponse.createByErrorMessage("id为空");
        }
        int row = hQrManageMapper.deleteByIds(ids);
        if (row > 0) {
            return ServerResponse.createBySuccessMessage("删除成功");
        }
        return ServerResponse.createByErrorMessage("删除失败");
    }

    @Override
    public ServerResponse<List<HQrManage>> getQrPath(OrgDept currentUserDept) {
        if (currentUserDept == null) {
            return ServerResponse.createByErrorMessage("部门为空");
        }
        List<HQrManage> list = hQrManageMapper.selectByDeptId(currentUserDept.getDeptUuid());
        if (CollectionUtils.isEmpty(list)) {
            return ServerResponse.createByErrorMessage("没有找到二维码");
        }
//        ServerResponse<List<HQrManage>> serverResponse=null;
//        for (HQrManage hQrManage : list){
//            serverResponse = this.contrastMd5(hQrManage.getQrCodeId(),hQrManage.getQrCodePath() );
//            if (!serverResponse.isSuccess()){
//                break;
//            }
//        }
//        //对比MD5
//        if (!serverResponse.isSuccess()) {
//            return serverResponse;
//        }
        return ServerResponse.createBySuccess(list);
    }


    @Override
    public ServerResponse<String> update(String userId, String model) {
        if (StringUtils.isBlank(model)) {
            return ServerResponse.createByErrorMessage("model是null");
        }
        JSONObject jsonObject = JSON.parseObject(model);
        String account_number = jsonObject.getString("account_number");
        if (StringUtils.isBlank(account_number)) {
            return ServerResponse.createByErrorMessage("账号不能为空");
        }
        String person_name = jsonObject.getString("person_name");
        if (StringUtils.isBlank(person_name)) {
            return ServerResponse.createByErrorMessage("联系人不能为空");
        }
        String person_phone = jsonObject.getString("person_phone");
        if (StringUtils.isBlank(person_phone)) {
            return ServerResponse.createByErrorMessage("联系电话不能为空");
        }
        String type = jsonObject.getString("type");
        if (StringUtils.isBlank(type)){
            return ServerResponse.createByErrorMessage("支付类型为空");
        }
        String remark = jsonObject.getString("remark");
        HResourceRelation hResourceRelation = jsonObject.getObject("image", HResourceRelation.class);
        if(hResourceRelation==null){
            return ServerResponse.createByErrorMessage("图片为空");
        }
        String path = hResourceRelation.getPath();
        if (StringUtils.isBlank(path)) {
            return ServerResponse.createByErrorMessage("path为空");
        }
        String resouceId = hResourceRelation.getResouceId();
        if (StringUtils.isBlank(resouceId)) {
            return ServerResponse.createByErrorMessage("resouceId为空");
        }
        String id = JSON.parseObject(model).getString("id");
        if (StringUtils.isBlank(id)){
            return ServerResponse.createByErrorMessage("id为空");
        }
        HQrManage hQrManage = new HQrManage();
        hQrManage.setAccountNumber(account_number);
        hQrManage.setPersonName(person_name);
        hQrManage.setPersonPhone(person_phone);
        hQrManage.setQrCodeId(resouceId);
        hQrManage.setQrCodePath(path);
        hQrManage.setRemark(remark);
        hQrManage.setType(type);
        hQrManage.setModifyUser(userId);
        hQrManage.setId(id);
        int row = hQrManageMapper.updateByPrimaryKeySelective(hQrManage);
        if (row > 0) {
            return ServerResponse.createBySuccessMessage("更新成功");
        }
        return ServerResponse.createByErrorMessage("更新失败");
    }


    @Override
    public ServerResponse<String> save(String userId, OrgDept currentUserDept, String model) {
        if(StringUtils.isBlank(model)){
            return ServerResponse.createByErrorMessage("model不能为空");
        }
        if (currentUserDept == null) {
            return ServerResponse.createByErrorMessage("没有找到部门");
        }
        JSONObject jsonObject = JSON.parseObject(model);
        String account_number = jsonObject.getString("account_number");
        if (StringUtils.isBlank(account_number)) {
            return ServerResponse.createByErrorMessage("账号不能为空");
        }
        String person_name = jsonObject.getString("person_name");
        if (StringUtils.isBlank(person_name)) {
            return ServerResponse.createByErrorMessage("联系人不能为空");
        }
        String person_phone = jsonObject.getString("person_phone");
        if (StringUtils.isBlank(person_phone)) {
            return ServerResponse.createByErrorMessage("联系电话不能为空");
        }
        String type = jsonObject.getString("type");
        if (StringUtils.isBlank(type)){
            return ServerResponse.createByErrorMessage("支付类型为空");
        }
        String remark = jsonObject.getString("remark");
        HResourceRelation hResourceRelation = jsonObject.getObject("image", HResourceRelation.class);
        if(hResourceRelation==null){
            return ServerResponse.createByErrorMessage("图片为空");
        }
        String path = hResourceRelation.getPath();
        if (StringUtils.isBlank(path)) {
            return ServerResponse.createByErrorMessage("path为空");
        }
        String resouceId = hResourceRelation.getResouceId();
        if (StringUtils.isBlank(resouceId)) {
            return ServerResponse.createByErrorMessage("resouceId为空");
        }
        HQrManage hQrManage = new HQrManage();
        hQrManage.setAccountNumber(account_number);
        hQrManage.setPersonName(person_name);
        hQrManage.setPersonPhone(person_phone);
        hQrManage.setQrCodeId(resouceId);
        hQrManage.setQrCodePath(path);
        hQrManage.setRemark(remark);
        hQrManage.setType(type);


        hQrManage.setId(FleaStringUtils.getGenerateUUID());
        hQrManage.setCreateUser(userId);
        hQrManage.setModifyUser(userId);
        hQrManage.setUuid(currentUserDept.getDeptUuid());
        int row = hQrManageMapper.insertSelective(hQrManage);
        if (row > 0) {
            return ServerResponse.createBySuccessMessage("添加成功");
        }
        return ServerResponse.createByErrorMessage("添加失败");
    }

    //对比md5
    private ServerResponse<List<HQrManage>> contrastMd5(String imagePath, String imageId) {
        WebFileupload file = fileUploadMapper.selectByPrimaryKey(imageId);
        if (file == null) {
            return ServerResponse.createByErrorMessage("没有找到该文件");
        }
        String path = PropertiesUtil.getProperty("file.upload.path");
        path+=imagePath;
        File file1 = new File(path);
        if (!file1.exists()){
            return ServerResponse.createByErrorMessage("没有找到图片"+path);
        }
        try {
            String value = this.getMd5ByFile(file1);
            if (StringUtils.equals(value, file.getMd5())) {
                return ServerResponse.createBySuccess();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return ServerResponse.createByErrorMessage("二维码可能被篡改，请联系管理员");
    }

    private String getMd5ByFile(File file) throws FileNotFoundException {
        String value = null;
        FileInputStream in = new FileInputStream(file);
        try {
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return value;
    }
}
